package com.dog.basics.netty.business.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dog.basics.bean.model.mtkj.MtDeviceLock;
import com.dog.basics.common.util.SpringContextUtils;
import com.dog.basics.netty.business.IBusinessServer;
import com.dog.basics.netty.protobuf.dto.DogNewsContentDto;
import com.dog.basics.netty.util.SessionSocketHolder;
import com.dog.basics.service.mtkj.IMtDeviceLockService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.log4j.Log4j2;

import java.util.List;

/**
 * @description: 登录消息 - 请求
 * @author: He
 * @date: Created in 2020/10/8 18:31
 * @version: 1.0
 * @modified By:
 */
@Log4j2
public class ResponseHandlerImplLogin implements IBusinessServer<DogNewsContentDto.Message> {

    /**
     * @功能描述: 执行.登录消息
     * @author He
     * @date 2020年10月8日
     */
    @Override
    public void businessHandler(ChannelHandlerContext ctx, DogNewsContentDto.Message msg) throws InterruptedException {
        log.info("登录请求:{}", msg.toString());
        // 判断账号密码是否为空
        if (ObjectUtil.isNull(msg.getDevCode())) {
            closeLogin(ctx, msg);
            return;
        }
        // 根据账号|Code 获取设备信息并且校验登录
        List<MtDeviceLock> deviceLocks = SpringContextUtils.getBean(IMtDeviceLockService.class).list(Wrappers.<MtDeviceLock>lambdaQuery().eq(MtDeviceLock::getDevCode, msg.getDevCode()));
        if (CollUtil.isEmpty(deviceLocks)) {
            closeLogin(ctx, msg);
            return;
        }
        // 判断当前是否已有此设备的连接
        NioSocketChannel lodNioSocketChannel = SessionSocketHolder.get(deviceLocks.get(0).getId());
        if (ObjectUtil.isNotNull(lodNioSocketChannel)) {
            lodNioSocketChannel.writeAndFlush(DogNewsContentDto.Message.newBuilder().setMsgType(msg.getMsgType()).setMsgCode(2));
            lodNioSocketChannel.close();
            SessionSocketHolder.logu(deviceLocks.get(0).getId());
        }
        // 判断是否校验密码   [ -暂废不校验- ]
        if (Boolean.FALSE) {
            // 登录失败则给与返回消息告诉用户登录失败
            closeLogin(ctx, msg);
            return;
        }
        // 判断是否锁定机器
        if (Boolean.TRUE) {
            // 锁定机器则直接告知硬件

        }
        // 修改在线状态并且修改蓝牙MAC地址
        MtDeviceLock deviceLock = new MtDeviceLock();
        deviceLock.setId(deviceLocks.get(0).getId());
        deviceLock.setDevBluetoothName(msg.getSecretKey());
        // 判断未初始化 - 初始化
        if (Validator.equal(deviceLocks.get(0).getDevInitializeState(), 0)) {
            deviceLock.setDevInitializeState(1);
        }
        deviceLock.setDevOnlineState(1);
        deviceLock.setRemarksTow(msg.getImeiVersion());
        deviceLock.setUpdateTime(DateUtil.currentSeconds());
        // 修改 在线 - 状态
        SpringContextUtils.getBean(IMtDeviceLockService.class).updateById(deviceLock);
        // 登录成功添加 SessionMap 中数据
        SessionSocketHolder.addAll(deviceLocks.get(0).getId(), (NioSocketChannel) ctx.channel());
        ctx.channel().writeAndFlush(DogNewsContentDto.Message.newBuilder().setMsgType(msg.getMsgType()).setMsgCode(1).setTimeStamp((int) DateUtil.currentSeconds()));
    }

    /**
     * 关闭登录 - 失败返回
     *
     * @param ctx
     * @param msg
     */
    public void closeLogin(ChannelHandlerContext ctx, DogNewsContentDto.Message msg) {
        ctx.channel().writeAndFlush(DogNewsContentDto.Message.newBuilder().setMsgType(msg.getMsgType()).setMsgCode(2));
        ctx.channel().close();
    }
}
